package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.vo.dzzf.base.qxsjz.entity.MergeTransLog;
import com.wtkj.vo.dzzf.base.qxsjz.entity.PortalTransOut;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.CorrectMergeTransVehPlateDao;
import org.apache.commons.lang.StringUtils;
import org.javatuples.Pair;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 修改待合并原始交易车牌号服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/20
 */
@Service
@Slf4j
public class CorrectMergeTransVehPlateService {

    @Resource
    private CorrectMergeTransVehPlateDao correctMergeTransVehPlateDao;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    private final TransactionTemplate transactionTemplate;

    public CorrectMergeTransVehPlateService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void correct() {
        //车牌号不一致的passId
        List<MergeTransLog> mergeTransLogList = correctMergeTransVehPlateDao.queryErrorMergeLog();
        log.info("共查询到{}个对应原始交易车牌号不一致的passId", mergeTransLogList.size());

        mergeTransLogList.forEach(mergeTransLog ->
                taskExecutor.execute(new CorrectMergeTransVehPlateThread(mergeTransLog)));

    }


    class CorrectMergeTransVehPlateThread implements Runnable {

        private final MergeTransLog mergeTransLog;

        CorrectMergeTransVehPlateThread(MergeTransLog mergeTransLog) {
            this.mergeTransLog = mergeTransLog;
        }

        @Override
        public void run() {
            try {
                transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                        correctSingle();
                    }
                });
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

        private void correctSingle() {

            String passId = mergeTransLog.getPassId();

            List<PortalTransOut> transVehPairList =
                    correctMergeTransVehPlateDao.queryPortalTransOutByMergeTransLog(mergeTransLog);
            log.info("passId：{}，查询出{}条原始交易记录", passId, transVehPairList.size());

            if (transVehPairList.isEmpty()) {
                return;
            }


            long distinctCnt = transVehPairList.stream()
                    .map(PortalTransOut::getEtcCardId)
                    .distinct()
                    .count();

            if (distinctCnt != 1) {
                log.error("对应原始交易卡号不一致，跳过处理");
                return;
            }
            String etcCardId = transVehPairList.get(0).getEtcCardId();


            if (!StringUtils.startsWith(etcCardId, "61")) {
                log.info("非陕西省卡，跳过处理");
                return;
            }


            if ("61010000000000000000".equals(etcCardId)) {
                log.info("错误的卡号，跳过处理");
                return;
            }


            Map<String, Long> vehPlateCntMap = transVehPairList.stream()
                    .map(PortalTransOut::getVehiclePlate)
                    .collect(Collectors.groupingBy(v -> v, Collectors.counting()));
            log.info("按照车牌号分组：{}", vehPlateCntMap);

            Map<Integer, Long> vehColorCntMap = transVehPairList.stream()
                    .map(PortalTransOut::getVehicleColor)
                    .collect(Collectors.groupingBy(v -> v, Collectors.counting()));
            log.info("按照车牌颜色分组：{}", vehColorCntMap);


            /*if (vehPlateCntMap.size() > 2) {
                log.error("车牌号分组超过2个，跳过处理");
                return;
            }

            if (vehColorCntMap.size() > 2) {
                log.error("车牌颜色分组超过2个，跳过处理");
                return;
            }*/

            String eCardNo = etcCardId.substring(4);
            Pair<String, Integer> vehPair = correctMergeTransVehPlateDao.queryVehPlateByECardNo(eCardNo);

            if (vehPair == null) {
                log.info("获取不到卡号：{}对应的车牌信息", etcCardId);
                return;
            }

            String rightVehPlate = vehPair.getValue0();
            Integer rightVehColor = vehPair.getValue1();

            /*if (vehPlateCntMap.keySet().stream().noneMatch(v -> Objects.equals(v, rightVehPlate))) {
                log.error("对应原始交易不存在正确车牌号：{}，跳过处理", rightVehPlate);
                return;
            }

            if (vehColorCntMap.keySet().stream().noneMatch(v -> Objects.equals(v, rightVehColor))) {
                log.info("对应原始交易不存在正确车牌颜色：{}，跳过处理", rightVehColor);
                return;
            }*/


            transVehPairList.forEach(transVehPair -> {
                String transactionId = transVehPair.getTransactionId();
                String vehPlate = transVehPair.getVehiclePlate();
                Integer vehicleColor = transVehPair.getVehicleColor();

                if (!StringUtils.equals(rightVehPlate, vehPlate)) {
                    correctMergeTransVehPlateDao.updateTransVehPlate(transactionId, rightVehPlate);
                }

                if (!Objects.equals(rightVehColor, vehicleColor)) {
                    correctMergeTransVehPlateDao.updateTransVehColor(transactionId, rightVehColor);
                }
            });

            correctMergeTransVehPlateDao.deleteMergeLog(passId);

        }
    }

}
